from datetime import datetime, timedelta
from flask import render_template, session, redirect, url_for, current_app, request, flash

from . import main
# from .forms import NameForm
from .forms import Form_create_user, Form_query_dataset, Form_submit_job, Form_query_job, Form_kill_job, Form_query_resource, Form_login

from .. import db
from ..models import User, Job, Resource
import os
import uuid


@main.route('/', methods=['GET', 'POST'])
def index():
    form_create_user = Form_create_user()
    form_login = Form_login()
    form_query_dataset = Form_query_dataset()
    form_submit_job = Form_submit_job()
    form_query_job = Form_query_job()
    form_kill_job = Form_kill_job()
    form_query_resource = Form_query_resource()

    if not session.get('login', False):
        return redirect(url_for('main.create_user'))

    return render_template('index.html', name=session.get('name'),
            known=session.get('known', False), current_time=datetime.utcnow(),
            login=session.get('login', False),
            query_dataset=session.get('query_dataset', False), datasets=session.get('datasets', []),
            query_job=session.get('query_job', False), jobs=session.get('jobs', []),
            query_resource=session.get('query_resource', False), resources=session.get('resources', []),
            form_create_user=form_create_user, form_query_dataset=form_query_dataset,
            form_submit_job=form_submit_job, form_query_job=form_query_job,
            form_kill_job=form_kill_job, form_query_resource=form_query_resource,
            form_login=form_login)

@main.route('/user/create', methods=['GET', 'POST'])
def create_user():
    form_create_user = Form_create_user()
    form_login = Form_login()

    # print(request.method) #
    # print(request.url) #
    # print(request.cookies) #
    # print(request.path)  # 
    # print(request.args) #
    # print(request.args.get("id")) #
    # print(request.args["name"]) #
    # print(request.args.to_dict()) #

    if form_create_user.validate_on_submit():
        print('create_user============')
        current_app.config['LOGGER'].info('create_user============')
        # user = User.query.filter_by(username=form.name.data).first()
        # if user is None:
        #     user = User(username=form.name.data)
        #     db.session.add(user)
        #     db.session.commit()
        #     session['known'] = False
        #     if current_app.config['FLASKY_ADMIN']:
        #         send_email(current_app.config['FLASKY_ADMIN'], 'New User',
        #                    'mail/new_user', user=user)
        # else:
        #     session['known'] = True
        # session['name'] = form.name.data
        user = db.users.find_one({"username": form_create_user.name.data})
        if user is None:
            #todo
            # userid = 
            # password =
            db.users.insert_one({"username": form_create_user.name.data, "password": form_create_user.password.data})
            flash("Create user: %s  success" % form_create_user.name.data)
            session['known'] = False
        else:
            session['known'] = True
            flash("User has exited!")
        session['name'] = form_create_user.name.data
    return render_template('login.html', name=session.get('name'),
            known=session.get('known', False), current_time=datetime.utcnow(),
            login=session.get('login', False),
            form_create_user=form_create_user, form_login=form_login)

@main.route('/user/login', methods=['GET', 'POST'])
def login():
    form_create_user = Form_create_user()
    form_login = Form_login()

    # print(request.method) #
    # print(request.url) #
    # print(request.cookies) #
    # print(request.path)  # 
    # print(request.args) #
    # print(request.args.get("id")) #
    # print(request.args["name"]) #
    # print(request.args.to_dict()) #

    if form_login.validate_on_submit():
        print('login============')
        current_app.config['LOGGER'].info('login============')
        user = db.users.find_one({"username": form_login.name.data})
        if user is None:
            #todo
            # userid = 
            # password =
            print('login fail============')
            current_app.config['LOGGER'].info('login fail============')
            flash("User: %s not exists" % form_login.name.data)
            session['login'] = False
        else:
            db_password = user['password']
            input_password = form_login.password.data
            if (db_password != input_password):
                flash("password is wrong" % form_login.name.data)
                session['login'] = False
            print('login success============')
            current_app.config['LOGGER'].info('login success============')
            flash("login success!")
            session['login'] = True
            session.permanent = True 
            app = current_app._get_current_object() 
            app.permanent_session_lifetime = timedelta(days=1)
            session['name'] = form_login.name.data
            return redirect(url_for('main.index'))
    return render_template('login.html', name=session.get('name'),
            known=session.get('known', False), current_time=datetime.utcnow(),
            login=session.get('login', False),
            form_create_user=form_create_user, form_login=form_login)


@main.route('/user/logout', methods=['GET', 'POST'])
def logout():
    session.clear()
    return redirect(url_for('main.create_user'))

@main.route('/api/dataset/query', methods=['GET', 'POST'])
def query_dataset():
    if not session.get('login', False):
        return redirect(url_for('main.create_user'))

    form_create_user = Form_create_user()
    form_login = Form_login()
    form_query_dataset = Form_query_dataset()
    form_submit_job = Form_submit_job()
    form_query_job = Form_query_job()
    form_kill_job = Form_kill_job()
    form_query_resource = Form_query_resource()

    if form_query_dataset.validate_on_submit():
        print('query_dataset============')
        current_app.config['LOGGER'].info('query_dataset============')
        db_datasets = db.datasets.find({})
        if db_datasets is None:
            session['query_dataset'] = False
            print("session['query_dataset'] = False")
        else:
            session['query_dataset'] = True
            print("session['query_dataset'] = True")
        session['name'] = form_query_dataset.name.data
        session['datasets'] = []
        for col in db_datasets:
            print("===================")
            print(col['dataset'])
            session['datasets'].append(col['dataset'])
        return redirect(url_for('main.index'))

    return render_template('index.html', name=session.get('name'),
            known=session.get('known', False), current_time=datetime.utcnow(),
            login=session.get('login', False),
            query_dataset=session.get('query_dataset', False), datasets=session.get('datasets', []),
            query_job=session.get('query_job', False), jobs=session.get('jobs', []),
            query_resource=session.get('query_resource', False), resources=session.get('resources', []),
            form_create_user=form_create_user, form_query_dataset=form_query_dataset,
            form_submit_job=form_submit_job, form_query_job=form_query_job,
            form_kill_job=form_kill_job, form_query_resource=form_query_resource,
            form_login=form_login)

@main.route('/api/job/submit', methods=['GET', 'POST'])
def submit_job():
    if not session.get('login', False):
        return redirect(url_for('main.create_user'))    

    form_create_user = Form_create_user()
    form_login = Form_login()
    form_query_dataset = Form_query_dataset()
    form_submit_job = Form_submit_job()
    form_query_job = Form_query_job()
    form_kill_job = Form_kill_job()
    form_query_resource = Form_query_resource()

    print('receive file============')
    current_app.config['LOGGER'].info('receive file============')
    if form_submit_job.validate_on_submit():
        user_code = form_submit_job.job_code.data
        # user_code = request.files['file']
        print(user_code)
        print('receive file============')
        current_app.config['LOGGER'].info('receive file============')
        basepath = os.path.dirname(__file__)
        upload_path = os.path.join(basepath, 'upload_files', user_code.filename)
        file_dir = os.path.join(basepath, 'upload_files')
        current_app.config['LOGGER'].info(upload_path)        
        if not os.path.exists(file_dir):
            os.makedirs(file_dir)
        user_code.save(upload_path)

        jobid = uuid.uuid4()
        db.jobs.insert_one({"username": form_create_user.name.data, "jobid": jobid, "codedir": upload_path, "status": 'WAITING', "process": None})

        flash('Upload Job Success, JobId is %s, status is %s' % (jobid, "WATING") )
        return redirect(url_for('main.index'))
        #return "Upload success"
    else:
        print('not receive file============')
        current_app.config['LOGGER'].info('not receive file============')        
    # return render_template('index.html', form=form, name=session.get('name'),
    #         known=session.get('known', False), current_time=datetime.utcnow())
    return render_template('index.html', name=session.get('name'),
            known=session.get('known', False), current_time=datetime.utcnow(),
            login=session.get('login', False),
            query_dataset=session.get('query_dataset', False), datasets=session.get('datasets', []),
            query_job=session.get('query_job', False), jobs=session.get('jobs', []),
            query_resource=session.get('query_resource', False), resources=session.get('resources', []),
            form_create_user=form_create_user, form_query_dataset=form_query_dataset,
            form_submit_job=form_submit_job, form_query_job=form_query_job,
            form_kill_job=form_kill_job, form_query_resource=form_query_resource,
            form_login=form_login)

@main.route('/api/job/query', methods=['GET', 'POST'])
def query_job():
    if not session.get('login', False):
        return redirect(url_for('main.create_user'))

    form_create_user = Form_create_user()
    form_login = Form_login()
    form_query_dataset = Form_query_dataset()
    form_submit_job = Form_submit_job()
    form_query_job = Form_query_job()
    form_kill_job = Form_kill_job()
    form_query_resource = Form_query_resource()

    if form_query_job.validate_on_submit():
        print('query_job============')
        current_app.config['LOGGER'].info('query_job============')
        db_jobs = db.jobs.find({"username": form_query_job.name.data})
        if db_jobs is None:
            session['query_job'] = False
        else:
            session['query_job'] = True
        session['name'] = form_query_dataset.name.data
        session['jobs'] = []
        for col in db_jobs:
            print("===================")
            print(col['jobid'])
            new_col = {}
            for k, v in col.items():
                new_col[k] = str(v)
            session['jobs'].append(new_col)
        return redirect(url_for('main.index'))


    return render_template('index.html', name=session.get('name'),
            known=session.get('known', False), current_time=datetime.utcnow(),
            login=session.get('login', False),
            query_dataset=session.get('query_dataset', False), datasets=session.get('datasets', []),
            query_job=session.get('query_job', False), jobs=session.get('jobs', []),
            query_resource=session.get('query_resource', False), resources=session.get('resources', []),
            form_create_user=form_create_user, form_query_dataset=form_query_dataset,
            form_submit_job=form_submit_job, form_query_job=form_query_job,
            form_kill_job=form_kill_job, form_query_resource=form_query_resource,
            form_login=form_login)

@main.route('/api/job/kill', methods=['GET', 'POST'])
def kill_job():
    if not session.get('login', False):
        return redirect(url_for('main.create_user'))

    form_create_user = Form_create_user()
    form_login = Form_login()
    form_query_dataset = Form_query_dataset()
    form_submit_job = Form_submit_job()
    form_query_job = Form_query_job()
    form_kill_job = Form_kill_job()
    form_query_resource = Form_query_resource()

    if form_kill_job.validate_on_submit():
        print('kill_job============')
        current_app.config['LOGGER'].info('kill_job============')

        return redirect(url_for('main.index'))

    return render_template('index.html', name=session.get('name'),
            known=session.get('known', False), current_time=datetime.utcnow(),
            login=session.get('login', False),
            query_dataset=session.get('query_dataset', False), datasets=session.get('datasets', []),
            query_job=session.get('query_job', False), jobs=session.get('jobs', []),
            query_resource=session.get('query_resource', False), resources=session.get('resources', []),
            form_create_user=form_create_user, form_query_dataset=form_query_dataset,
            form_submit_job=form_submit_job, form_query_job=form_query_job,
            form_kill_job=form_kill_job, form_query_resource=form_query_resource,
            form_login=form_login)


@main.route('/api/resource/query', methods=['GET', 'POST'])
def query_resource():
    if not session.get('login', False):
        return redirect(url_for('main.create_user'))

    form_create_user = Form_create_user()
    form_login = Form_login()
    form_query_dataset = Form_query_dataset()
    form_submit_job = Form_submit_job()
    form_query_job = Form_query_job()
    form_kill_job = Form_kill_job()
    form_query_resource = Form_query_resource()

    if form_query_resource.validate_on_submit():
        print('query_dataset============')
        current_app.config['LOGGER'].info('query_dataset============')
        db_resources = db.resources.find({})
        if db_resources is None:
            session['query_resource'] = False
            print("session['query_resource'] = False")
        else:
            session['query_resource'] = True
            print("session['query_resource'] = True")
        session['name'] = form_query_resource.name.data
        session['resources'] = []
        for col in db_resources:
            print("===================")
            print(col['nodeid'])
            new_col = {}
            for k, v in col.items():
                new_col[k] = str(v)
            session['resources'].append(new_col)
        return redirect(url_for('main.index'))

    return render_template('index.html', name=session.get('name'),
            known=session.get('known', False), current_time=datetime.utcnow(),
            login=session.get('login', False),
            query_dataset=session.get('query_dataset', False), datasets=session.get('datasets', []),
            query_job=session.get('query_job', False), jobs=session.get('jobs', []),
            query_resource=session.get('query_resource', False), resources=session.get('resources', []),
            form_create_user=form_create_user, form_query_dataset=form_query_dataset,
            form_submit_job=form_submit_job, form_query_job=form_query_job,
            form_kill_job=form_kill_job, form_query_resource=form_query_resource,
            form_login=form_login)

